package com.aluka.furme.lm.configuration;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.system.SystemUtil;
import com.aluka.furme.lm.utils.JsonFileUtil;
import com.google.common.collect.Maps;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

@Slf4j
@Configuration
@ConfigurationProperties(prefix = "lm")
@EnableConfigurationProperties(GlobalDaoConfiguration.class)
public class GlobalDaoConfiguration {

    private static final String DEFAULT_SUFFIX_PATH = "/lm-data";

    private static final Map<String,Object> CONFIG_CACHE = Maps.newHashMap();

    @Getter
    @Setter
    private static Map<String, String> properties = Maps.newHashMap();

    @PostConstruct
    public void init(){
        initDefaultConfig();
        initDefaultUser();
        initDefaultNav();
    }

    public static Object getConfig(String configKey){
        Object o = CONFIG_CACHE.get(configKey);
        if(properties != null && properties.containsKey(configKey)){
            o = properties.get(configKey);
        }
        Assert.notNull(o,"系统配置项["+configKey+"]数据缺少，可以在启动参数中指定: -Dlm.properties." + configKey);
        return o;
    }

    public static Object getConfig(String configKey,Object defaultValue){
        Object o = CONFIG_CACHE.get(configKey);
        return o == null ? defaultValue : o;
    }

    /**
     * 获取当前系统编码
     *
     * @return charset
     */
    public static Charset getCharset() {
        Charset charset = null;
        if (SystemUtil.getOsInfo().isLinux()) {
            charset = CharsetUtil.CHARSET_UTF_8;
        } else if (SystemUtil.getOsInfo().isMac()) {
            charset = CharsetUtil.CHARSET_UTF_8;
        } else {
            charset = CharsetUtil.CHARSET_GBK;
        }
        return charset;
    }

    public static void putConfig(String configKey,Object configValue){
        CONFIG_CACHE.put(configKey,configValue);
    }

    public static String getProfilePath(){
        return getConfig(ConfigBean.ROOT_PATH).toString();
    }

    public static String getTempPath(){
        String tempPath = String.format("%s/temp", getProfilePath());
        File tempDir = new File(tempPath);
        if(!tempDir.exists()){
            boolean b = tempDir.mkdirs();
        }
        return tempPath;
    }

    public static class ConfigBean{
        /**
         * 数据根目录
         */
        public static final String ROOT_PATH = "root_path";
    }

    public static class FileBean{
        /** 配置数据文件 */
        public static final String CONFIG = "config/config.json";
        /** 用户数据文件 */
        public static final String USER = "data/user.json";
        /** 导航数据文件 */
        public static final String NAV = "data/nav.json";
    }

    public static void initDefaultConfig(){
        try {
            if(CONFIG_CACHE.get(ConfigBean.ROOT_PATH) == null){
                if(SystemUtil.getOsInfo().isLinux()){
                    GlobalDaoConfiguration.putConfig(GlobalDaoConfiguration.ConfigBean.ROOT_PATH,"/opt/" + DEFAULT_SUFFIX_PATH);
                }else if(SystemUtil.getOsInfo().isWindows()){
                    GlobalDaoConfiguration.putConfig(GlobalDaoConfiguration.ConfigBean.ROOT_PATH,"C:/" + DEFAULT_SUFFIX_PATH);
                }
            }
            String configFilePath = String.format("%s/%s", GlobalDaoConfiguration.getProfilePath(), GlobalDaoConfiguration.FileBean.CONFIG);
            JSONObject configJson = null;
            if(new File(configFilePath).exists()){
                configJson = (JSONObject) JsonFileUtil.readJson(configFilePath);
            }else{
                ClassPathResource configResource = new ClassPathResource("config/default-config.json");
                String configInfo= IOUtils.toString(configResource.getInputStream(), Charsets.toCharset(CharsetUtil.UTF_8));
                configJson = JSONUtil.parseObj(configInfo);
                JsonFileUtil.saveJson(configFilePath,configJson);
            }

            configJson.forEach((k,v)->{
                GlobalDaoConfiguration.putConfig(k,((JSONObject)v).getStr("configValue"));
            });
            log.info("系统配置信息初始化成功...");
        } catch (IOException e) {
            throw new RuntimeException("配置文件丢失",e);
        }
    }

    public static void initDefaultUser(){
        try {
            if(!new File(String.format("%s/%s", GlobalDaoConfiguration.getProfilePath(), GlobalDaoConfiguration.FileBean.USER)).exists()){
                ClassPathResource userResource = new ClassPathResource("config/default-user.json");
                String userInfo = IOUtils.toString(userResource.getInputStream(), Charsets.toCharset(CharsetUtil.UTF_8));
                JSONObject userJson = JSONUtil.parseObj(userInfo);
                JsonFileUtil.saveJson(String.format("%s/%s", GlobalDaoConfiguration.getProfilePath(), GlobalDaoConfiguration.FileBean.USER),userJson);
            }
        } catch (IOException e) {
            throw new RuntimeException("默认用户文件丢失",e);
        }
    }
    public static void initDefaultNav(){
        try {
            if(!new File(String.format("%s/%s", GlobalDaoConfiguration.getProfilePath(), FileBean.NAV)).exists()){
                ClassPathResource navResource = new ClassPathResource("config/default-nav.json");
                String navInfo = IOUtils.toString(navResource.getInputStream(), Charsets.toCharset(CharsetUtil.UTF_8));
                JSONObject navJson = JSONUtil.parseObj(navInfo);
                JsonFileUtil.saveJson(String.format("%s/%s", GlobalDaoConfiguration.getProfilePath(), GlobalDaoConfiguration.FileBean.NAV), navJson);
            }
        } catch (IOException e) {
            throw new RuntimeException("默认菜单文件丢失",e);
        }
    }
}
